/**
 * 
 */
package com.nannytools.util;


import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author alex
 *
 */
public class DBConnection {
	//Connection variables
private static Connection conn;
private static Statement statement;
private static ResultSet selectResultSet;
private Logger log;

	public DBConnection() {
		//get a connection object
		try {
			Class.forName(ConnectionStaticVariables.CONNECTION_CLASS);
			conn = DriverManager.getConnection(ConnectionStaticVariables.CONNECTION_STRING, 
					ConnectionStaticVariables.CONNECTION_USERNAME, ConnectionStaticVariables.CONNECTION_PASSWORD);
			log = Logger.getLogger("DBConnection");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//Open a public connection
	public DBConnection openConn() {
		return new DBConnection();
	}
	
	//Execute select query
	public ResultSet executeSelectQuery(String selectQuerySQL) {
		try {
			statement = conn.createStatement();
			selectResultSet = statement.executeQuery(selectQuerySQL);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return selectResultSet;
	}
	
	public String executeUpdateQuery (String updateQuerySQL) {
		try {
			statement = conn.createStatement();
			statement.executeUpdate(updateQuerySQL);
			return "0";
		} catch (Exception e){
			return "1";
		}
	}
	
	public int[] executeInsertQuery (String insertQuerySQL) {
		try {
			statement = conn.createStatement();
			int[] autoGeneratedKeys = new int[100];
			statement.execute(insertQuerySQL, autoGeneratedKeys);
			return autoGeneratedKeys;
		} catch (Exception e) {
			return null;
		}
	}
	
	public void closeConnection() throws SQLException {
		try {
			conn.close();
		} catch (SQLException e) {
			log.info("SQLExcetion Thrown during closing of the connection " + e.toString());
		}
	}
	
}
